// 
// Copyright (c) 2006-2009 Ben Motmans
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Author(s):
//    Ben Motmans <ben.motmans@gmail.com>
//

using System;
using System.Threading;
using System.Diagnostics;
using System.Collections.Generic;

namespace Anculus.Core
{
	//TODO: read http://www.pluralsight.com/community/blogs/mike/archive/2004/12/13/3905.aspx
	public abstract class AbstractDispatcher : IDispatcher
	{
		protected const int LockTimeout = 2000;
		protected int threadId;

		protected ulong queueIndex;
		protected bool queueIndexOverflow;
		
		protected Dictionary<ulong, IDispatchContainer> queue;

		#region IDispatcher
		public virtual void Initialize ()
		{
			threadId = Thread.CurrentThread.ManagedThreadId;
			queueIndex = 1;
			queue = new Dictionary<ulong, IDispatchContainer> ();
		}
		
		public virtual void Shutdown ()
		{
			if (Monitor.TryEnter (this, LockTimeout)) {
				try {
					queue.Clear ();
				} finally {
					Monitor.Exit (this);
				}
			} else {
				//nothing
			}
		}

		public virtual ulong Dispatch (VoidDispatchHandler callback)
		{
			if (callback == null)
				throw new ArgumentNullException ("callback");

			VoidDispatchContainer container = new VoidDispatchContainer (callback, false);
			return QueueContainer (container);
		}

		public virtual ulong Dispatch (ObjectDispatchHandler callback, object param)
		{
			if (callback == null)
				throw new ArgumentNullException ("callback");

			ObjectDispatchContainer container = new ObjectDispatchContainer (callback, param, false);
			return QueueContainer (container);
		}

		public virtual ulong DispatchWithDelay (int delay, VoidDispatchHandler callback)
		{
			if (delay < 100 || delay == int.MaxValue)
				throw new ArgumentException ("delay must be >= 100 ms");
			if (callback == null)
				throw new ArgumentNullException ("callback");
			
			VoidDispatchContainer container = new VoidDispatchContainer (callback, false, delay, false);
			return QueueContainer (container);
		}

		public virtual ulong DispatchWithDelay (int delay, ObjectDispatchHandler callback, object param)
		{
			if (delay < 100 || delay == int.MaxValue)
				throw new ArgumentException ("delay must be >= 100 ms");
			if (callback == null)
				throw new ArgumentNullException ("callback");
			
			ObjectDispatchContainer container = new ObjectDispatchContainer (callback, param, false, delay, false);
			return QueueContainer (container);
		}

		public virtual ulong DispatchAtInterval (int interval, VoidDispatchHandler callback)
		{
			if (interval < 100 || interval == int.MaxValue)
				throw new ArgumentException ("interval must be >= 100 ms");
			if (callback == null)
				throw new ArgumentNullException ("callback");
			
			VoidDispatchContainer container = new VoidDispatchContainer (callback, false, interval, true);
			return QueueContainer (container);
		}

		public virtual ulong DispatchAtInterval (int interval, ObjectDispatchHandler callback, object param)
		{
			if (interval < 100 || interval == int.MaxValue)
				throw new ArgumentException ("interval must be >= 100 ms");
			if (callback == null)
				throw new ArgumentNullException ("callback");
			
			ObjectDispatchContainer container = new ObjectDispatchContainer (callback, param, false, interval, true);
			return QueueContainer (container);
		}

		public virtual ulong SyncDispatch (VoidDispatchHandler callback)
		{
			if (callback == null)
				throw new ArgumentNullException ("callback");
				
			if (!IsDispatchRequired ())
				throw new InvalidOperationException ("Calling thread is the same as the executing thread which will cause a deadlock.");
			
			VoidDispatchContainer container = new VoidDispatchContainer (callback, true);
			return QueueContainer (container);
		}

		public virtual ulong SyncDispatch (ObjectDispatchHandler callback, object param)
		{
			if (callback == null)
				throw new ArgumentNullException ("callback");
				
			if (!IsDispatchRequired ())
				throw new InvalidOperationException ("Calling thread is the same as the executing thread which will cause a deadlock.");
			
			ObjectDispatchContainer container = new ObjectDispatchContainer (callback, param, true);
			return QueueContainer (container);
		}

		public virtual ulong SyncDispatchWithDelay (int delay, VoidDispatchHandler callback)
		{
			if (delay < 100 || delay == int.MaxValue)
				throw new ArgumentException ("delay must be >= 100 ms");
			if (callback == null)
				throw new ArgumentNullException ("callback");
				
			if (!IsDispatchRequired ())
				throw new InvalidOperationException ("Calling thread is the same as the executing thread which will cause a deadlock.");
			
			VoidDispatchContainer container = new VoidDispatchContainer (callback, true, delay, false);
			return QueueContainer (container);
		}

		public virtual ulong SyncDispatchWithDelay (int delay, ObjectDispatchHandler callback, object param)
		{
			if (delay < 100 || delay == int.MaxValue)
				throw new ArgumentException ("delay must be >= 100 ms");
			if (callback == null)
				throw new ArgumentNullException ("callback");
				
			if (!IsDispatchRequired ())
				throw new InvalidOperationException ("Calling thread is the same as the executing thread which will cause a deadlock.");
				
			ObjectDispatchContainer container = new ObjectDispatchContainer (callback, param, true, delay, false);
			return QueueContainer (container);
		}

		public virtual bool ResetDelay (ulong uid)
		{
			if (uid == 0UL)
				throw new ArgumentNullException ("uid");
			
			if (Monitor.TryEnter (this, LockTimeout)) {
				try {
					IDispatchContainer container = null;
					if (queue.TryGetValue (uid, out container)) {
						container.RemainingDelay = container.Delay;
						return true;
					}
				} finally {
					Monitor.Exit (this);
				}
			} else {
				Log.Error ("Unable to aquire lock, ResetDelay failed.");
			}

			return false;
		}

		//TODO: should CancelDispatch 'kill' running items ??
		public virtual bool CancelDispatch (ulong uid)
		{
			if (uid == 0UL)
				throw new ArgumentNullException ("uid");
			
			if (Monitor.TryEnter (this, LockTimeout)) {
				try {
					IDispatchContainer container = null;
					if (queue.TryGetValue (uid, out container)) {
						container.RemainingDelay = 0;
						container.Delay = 0;
						container.RepeatDelay = false;
						
						queue.Remove (uid);
						return true;
					}
				} finally {
					Monitor.Exit (this);
				}
			} else {
				Log.Error ("Unable to aquire lock, CancelDispatch failed.");
			}

			return false;
		}

		public virtual bool CancelDelay (ulong uid)
		{
			if (uid == 0UL)
				throw new ArgumentNullException ("uid");
			
			if (Monitor.TryEnter (this, LockTimeout)) {
				try {
					IDispatchContainer container = null;
					if (queue.TryGetValue (uid, out container)) {
						ProcessContainer (uid, container, 0, true); //force processing
						return true;
					}
				} finally {
					Monitor.Exit (this);
				}
			} else {
				Log.Error ("Unable to aquire lock, CancelDelay failed.");
			}

			return false;
		}

		public virtual bool ChangeDelay (ulong uid, int delay)
		{
			if (delay < 100 || delay == int.MaxValue)
				throw new ArgumentException ("delay must be >= 100 ms");
			if (uid == 0UL)
				throw new ArgumentNullException ("uid");
			
			if (Monitor.TryEnter (this, LockTimeout)) {
				try {
					IDispatchContainer container = null;
					if (queue.TryGetValue (uid, out container)) {
						int oldDelay = container.Delay;
						container.Delay = delay;
							
						ProcessContainer (uid, container, oldDelay - delay, false); //negative msecPassed increases the remaining delay
						return true;
					}
				} finally {
					Monitor.Exit (this);
				}
			} else {
				Log.Error ("Unable to aquire lock, ChangeDelay failed.");
			}

			return false;
		}

		public virtual bool ChangeInterval (ulong uid, int interval)
		{
			return ChangeDelay (uid, interval);
		}

		public virtual bool IsDispatchRequired ()
		{
			return threadId != Thread.CurrentThread.ManagedThreadId;
		}
		#endregion

		#region Internals
		protected virtual ulong QueueContainer (IDispatchContainer container)
		{
			Log.Trace ();

			bool dispatchRequired = IsDispatchRequired ();
			if (container.IsSynchronous || container.IsTimed || dispatchRequired) {
				if (Monitor.TryEnter (this, LockTimeout)) {
					try {
						//I'll be damned if this happens, but you never know ...
						if (queueIndex == ulong.MaxValue) {
							queueIndex = 0UL;
							queueIndexOverflow = true;
						}

						if (queueIndexOverflow) {
							//only do costly ContainsKey checks if we are out of unique identifiers
							while (queue.ContainsKey (++queueIndex)) {}
							queue.Add (queueIndex, container);
						} else {
							queue.Add (++queueIndex, container);
						}
					} finally {
						Monitor.Exit (this);
					}
				} else {
					Log.Error ("Unable to aquire lock, Dispatch failed.");
					return 0UL;
				}
					
				if (Monitor.TryEnter (container, LockTimeout)) {
					try {
						WakeupProcessQueue (); //wake up the processing thread in order to dispatch as soon as possible
	
						if (container.IsSynchronous)
							Monitor.Wait (container);
					} finally {
						Monitor.Exit (container);
					}
				} else {
					Log.Error ("Unable to aquire container lock, Dispatch failed");
					return 0UL;
				}
			} else {
				//no need for a dispatch
				container.Execute ();
				return 0UL;
			}

			return queueIndex;
		}

		protected virtual void ProcessQueue (int msecPassed)
		{
			Log.Trace ();
			
			if (queue.Count == 0) {
				return;
			} else {
				if (Monitor.TryEnter (this, LockTimeout)) {
					try {
						List<ulong> uids = new List<ulong> (queue.Keys);
					
						foreach (ulong uid in uids)
							ProcessContainer (uid, queue[uid], msecPassed, false);
					} finally {
						Monitor.Exit (this);
					}
				} else {
					Log.Error ("Unable to aquire lock, Dispatch failed.");
				}
			}
		}

		protected virtual void ProcessContainer (ulong uid, IDispatchContainer container, int msecPassed, bool force)
		{
			Log.Trace ();
			
			//TODO: execute containers in a ThreadPool thread ??
			//TODO: remove Debug/Trace statements ??
			
			if (Monitor.TryEnter (container, LockTimeout)) {
				try {
					if (container.IsTimed) {
						container.RemainingDelay -= msecPassed;
						
						Log.Debug ("CONTAINER {0} REMAINING {1} (repeat={2}, delay={3})", uid, container.RemainingDelay, container.RepeatDelay, container.Delay);
						
						if (container.RemainingDelay <= 0 || force) {
							container.Execute ();
							
							//check if the delegate is executed at a given interval
							if (container.RepeatDelay)
								container.RemainingDelay =  container.Delay;
							else if (force)
								container.RemainingDelay = 0;
						}
					} else {
						//always execute
						container.Execute ();
					}
					
					//Monitor.TryEnter not needed, since this method is called by ProcessQueue
					if (!container.IsTimed || (!container.RepeatDelay && container.RemainingDelay <= 0)) {
						queue.Remove (uid);
						Log.Debug ("***** REMOVED {0} *****", uid);
					}
					
					if (container.Exception != null)
						Log.Error (container.Exception, "An error occured inside a dispatched method.");
					
					if (container.IsSynchronous)
						Monitor.PulseAll (container);
				} finally {
					Monitor.Exit (container);
				}
			} else {
				Log.Error ("Unable to aquire container lock, Dispatch failed.");
			}
		}
		
		// This method must call 'ProcessQueue' or any other method to process the queue from the target thread.
		protected abstract void WakeupProcessQueue ();
		#endregion
	}
}